package qsoft.omanga.common.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Loading {
	private static final Loading LOAD = new Loading();

	public static final Loading getInstance() {
		return LOAD;
	}

	private final int poolThreads = 3;
	private final Map<String, TaskLoad> threadLoads = Collections
			.synchronizedMap(new WeakHashMap<String, TaskLoad>());
	private final ExecutorService executor = Executors
			.newFixedThreadPool(poolThreads);

	/**
	 * 
	 * @param iv
	 *            imageView
	 * @param id
	 *            id of manga | image of chapter
	 * @param url
	 *            url of image manga
	 * @param sizeImage
	 *            type size of manga
	 */
	public void forceLoad(ImageView iv, String id, String url, String sizeImage) {
		Cache.getInstance().resetPurgeTimer();
		Bitmap bitmap = Cache.getInstance().getBitmapFromCache(url);
		if (bitmap == null) {
			if (!threadLoads.containsKey(url)
					|| (threadLoads.containsKey(url) && !threadLoads.get(url)
							.isAlive())) {
				iv.setImageDrawable(null);
				TaskLoad task = new TaskLoad(iv, id, url, sizeImage);
				threadLoads.put(url, task);
				task.setPriority(Thread.MAX_PRIORITY);
				executor.submit(task);
				Log.w("Task Item" + task.id, "INIT THREAD LOAD...");
			}
		} else {
			iv.setImageBitmap(bitmap);
		}
	}

	// private Bitmap loadBitmapFile(String[] key) {
	// if (DownloadImage.getInstance().threadDownloads.containsKey(key)
	// && DownloadImage.getInstance().threadDownloads.get(key)
	// .isAlive()) {
	// return null;
	// } else {
	// Log.i("LOAD FILE " + key[0], "LOAD FILE " + key[0] + " RUNNING..");
	// String fileName = FileUtil.getImageName(key[0], key[2]);
	// String fullName = FileUtil.getNameWithoutExtension(FileUtil.path,
	// fileName);
	// return BitmapFactory.decodeFile(fullName + FileUtil.EXTENSION_JPG);
	// }
	// }

	/**
	 * 
	 * @param id
	 *            id of manga
	 * @param txtURL
	 *            url of image manga
	 * @param sizeImage
	 *            type size of image manga
	 * @return Bitmap
	 */
	private Bitmap loadBitmapNet(String id, String txtURL, String sizeImage) {
		Bitmap bitmap = null;
		try {
			Log.i("LOAD NET" + id, "LOAD NET " + id + " RUNNING..");
			URLConnection conn;
			URL url = new URL(txtURL);
			conn = url.openConnection();
			conn.setUseCaches(true);
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
			// Download File
			// DownloadImage.getInstance().forceDownload(key, bitmap);
		} catch (MalformedURLException e) {
			Log.e("MalformedURLException", e.getMessage());
		} catch (IOException e) {
			Log.e("IOException", e.getMessage());
		}
		return bitmap;
	}

	/**
	 * 
	 * @author sontt
	 * 
	 */
	private class TaskLoad extends Thread {
		/**
         * 
         */
		private ImageView iv;
		/**
         * 
         */
		private String id;
		/**
         * 
         */
		private String url;
		/**
         * 
         */
		private String sizeImage;

		/**
		 * 
		 * @param iv
		 *            ImageView
		 * @param id
		 *            id of manga
		 * @param url
		 *            url of manga
		 * @param sizeImage
		 *            type size of manga
		 */
		public TaskLoad(ImageView iv, String id, String url, String sizeImage) {
			this.iv = iv;
			this.id = id;
			this.url = url;
			this.sizeImage = sizeImage;
		}

		@Override
		public void run() {
			if (this.equals(threadLoads.get(url)) && this.iv.getTag() != null
					&& this.iv.getTag().equals(url)) {
				Bitmap bitmap = null;
				// bitmap = loadBitmapFile(key);
				// if (bitmap == null) {
				bitmap = loadBitmapNet(id, url, sizeImage);
				// }
				if (bitmap != null) {
					Cache.getInstance().addBitmapToCache(url, bitmap);
					iv.setImageBitmap(bitmap);
					threadLoads.remove(url);
					Log.i("Load Item" + id, "Finish..");
				} else {
					iv.setImageDrawable(null);
					Log.i("Load Item" + id, "Not Finish..");
				}
			} else {
				iv.setImageDrawable(null);
				Log.i("Don't Load Correct Item" + id, "Failure..");
			}
		}
	}
}
